/*
* @Author: 窦子滨<zibin_5257@163.com>
* @Date: 2019-05-05 13:18
 */
package main

import (
	"errors"
	"strings"
	"sync"
)
//映射关系 存储 初始化从配置文件/数据库中读取
var Mapping=NewMappingManage()

type Mappinger interface {
	Add(key,v string)
	Delete(key string)
	Get(key string)(string,error)
	All()(v map[string]string)
	Handle(name string)(v string,err error)
}

func NewMappingManage() Mappinger{
	return &MappingManage{}
}

type MappingManage struct {
	mapping sync.Map
}

func (t *MappingManage) Add(key string,v string){
	t.mapping.Store(key,v)
}

func (t *MappingManage) Delete(key string){
	t.mapping.Delete(key)
}

func (t *MappingManage) Get(key string)(v string,err error){
	if n,ok:=t.mapping.Load(key);ok{
		v=n.(string)
	}else{
		err=errors.New("mapping not key")
	}
	return
}

func (t *MappingManage) All()(v map[string]string){
	v= make(map[string]string,0)
	t.mapping.Range(func(key, value interface{}) bool {
		v[key.(string)]=value.(string)
		return true
	})
	return
}

func (t *MappingManage) Handle(name string)(v string,err error){
	s:=strings.Split(name,"_")
	if len(s)<2{
		err=errors.New("MicroService Name error")
		return
	}
	v=strings.Join(s[1:],"_")

	log.Debug("映射前的方法名：[%s]",v)

	if !Config.Mapping.Switch{
		return v,nil
	}

	if a,err:=t.Get(name);err==nil{
		log.Debug("映射处理后的方法名：[%s]",v)
		return a,nil
	}

	log.Debug("映射最终返回的方法名：[%s]",v)

	return v,nil
}

